import json
import urllib
from urllib import request, parse

# url = 'https://httpbin.org/get?name=zdz'

# response = request.urlopen(url)
# print(response.status)
# print(response.read().decode('utf-8'))

# res = request.Request(url, headers={
#     "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36"
# }, method='GET')
#
# response = request.urlopen(res)
# data = response.read().decode('utf-8')
# data = json.loads(data)
# print(data,data['headers']['User-Agent'])


url = 'https://httpbin.org/post'
data = {'name': 'zdz', 'age': 10}
# data_str = parse.urlencode(data)
# data_bytes = data_str.encode('utf-8')
#
# res = request.Request(url, data=data_bytes, headers={
#     "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36",
#     # 表单格式
#     'Content-Type': 'application/x-www-form-urlencoded'
# }, method='POST')
#
# response = request.urlopen(res)
# data = response.read().decode('utf-8')
# data = json.loads(data)
# print(data, data['headers']['User-Agent'])

# 转换成json格式
data_json = json.dumps(data)
# 转换成字节流
data_bytes = data_json.encode('utf-8')

res = request.Request(url, data=data_bytes, headers={
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36",
    # JSON格式
    'Content-Type': 'application/json'
}, method='POST')

response = request.urlopen(res)
data = response.read().decode('utf-8')
data = json.loads(data)
print(data, data['headers']['User-Agent'])
